<?php
/**
 * Created by bianquan
 * User: ZhuYunlong
 * Email: 920200256@qq.com
 * Date: 2019/2/6
 * Time: 17:19
 */

namespace app\admin\logic\auth;


use app\admin\cache\RoleAuthCache;
use app\admin\enum\AuthEnum;
use app\admin\logic\RestLogic;
use app\admin\model\auth\Role as RoleModel;
use think\annotation\Inject;
use think\db\BaseQuery;

class Role extends RestLogic
{

    /**
     * @Inject()
     * @var \app\admin\model\auth\Role
     */
    protected $model;

    /**
     * 获取列表
     * @throws \think\db\exception\DbException
     */
    public function getList()
    {
        $query = $this->model->newQuery();
        $name = $this->getQuery('name');
        if ($name) {
            $query->where('role_name', 'like', "%$name%");
        }
        return $this->handleGetList($query, false);
    }

    /**
     * 获取角色对应绑定的api key
     * @param $roleID
     * @return array
     */
    public function getRoleApiKeys($roleID)
    {
        // 超级管理员直接返回所有key
        return (new \app\admin\model\auth\Api)
            ->when(AuthEnum::SUPER_ROLE !== $roleID, function ($query) use ($roleID) {
                /** @var RoleModel $role */
                $role = (new RoleModel())->find($roleID);
                /** @var BaseQuery $query */
                return $query->where('api_id', 'in', $role->api_ids);
            })
            ->column('api_key');
    }

    /**
     * 更新或添加操作的时候，表单赋值
     */
    protected function setForm()
    {
        $this->form = [
            'role_name' => input('role_name'),
            'role_desc' => input('role_desc'),
            'menu_ids' => input('menu_ids'),
            'half_menu_ids' => input('half_menu_ids'),
            'api_ids' => input('api_ids')
        ];
        if ($this->isUpdate) {
            //更新角色的话，需要更新权限缓存
            RoleAuthCache::instance()->saveCache($this->request->put($this->model->getPk()));
        }
    }
}